var dictKeyArray = [];
layui.use(['element','table','form','layer','laydate'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer;

    //日期
    laydate.render({
        elem: '#systemTime',
        trigger : 'click',
        type: 'datetime',
        //min: minDate()//设置min默认最小值
    });
    loadCommunityList();

    addDevice = function () {
        $("#resource_form")[0].reset();
        $("#upload_form").attr("disabled", false);
        $("#upload_form").attr("class", "layui-btn");
        layer.open({
            type: 1
            , title: '添加设备'
            , area: ['55%', '70%']
            , content: $('#uploadDiv')
        });
    };
    function loadCommunityList() {
        $.get('/zxkDevice/loadCommunityList', {}, function (result) {
            if(result != null){
                if(result.data != null){
                    var $opt_html = "";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.communityId + "'>" + item.communityName + "</option>";
                    });
                    $("#communityId").empty().append($opt_html);
                    $("#communityId2").empty().append($opt_html);
                    form.render('select');
                    loadBuildingList($("#communityId").val(),'blockId','unitId');
                }
            }

        });
    }
    table.render({
        elem: '#deviceTable'
        ,url:'/zxkDevice/list'
        ,title: '门禁设备管理'
        ,where: {type:'',name:''}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{field:'communityName', title:'小区',align:'center'}
            ,{field:'serialNum', title:'设备序列号',align:'center'}
            ,{field:'deviceMac', title:'MAC',align:'center'}
            ,{field:'deviceModel', title:'设备型号',align:'center'}
            ,{field:'deviceName', title:'设备别名',align:'center'}
            ,{field:'unitName', title:'所属单元',align:'center'}
            ,{field:'status', title:'状态',align:'center',templet:function (data) {
                    return parseStatus(data.status);
                }}
            ,{field:'createTime', title:'创建时间',  sort: true,templet:
                    function(data){
                        return formatTime(data.createTime);
                    }}
            ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',width:220}
        ]]
        ,page: true
    });

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    form.on('select(communityId)',function (data) {
        loadBuildingList(data.value,'blockId','unitId');
    });
    form.on('select(communityId2)',function (data) {
        loadBuildingList(data.value,'blockId2','unitId2');
    });

    form.on('select(blockId)',function (data) {
        loadUnitList(data.value,'unitId');
    });
    form.on('select(blockId2)',function (data) {
        loadUnitList(data.value,'unitId2');
    });

    function loadBuildingList(val,blockId,unitId,selectedBlock,selectedUnit){
        $.get('/zxkDevice/loadBuildingList', {communityId:val}, function (result) {
            $("#"+blockId).empty();
            $("#"+unitId).empty();
            if(result != null){
                if(result.data != null){
                    var $opt_html = "";
                    $.each(result.data, function (index, item) {
                        $opt_html += "<option value='" + item.lyxxId + "'>" + item.lyxxName + "</option>";
                        if(!hasDictKey(item.lyxxId)){
                            var obj = {"key":item.lyxxId, "data":item.data};
                            dictKeyArray.push(obj);
                        }
                    });
                    $("#"+blockId).empty().append($opt_html);
                    if(selectedBlock){
                        $("#"+blockId).val(selectedBlock);
                    }
                    form.render('select');
                    loadUnitList($("#"+blockId).val(),unitId,selectedUnit);
                }
            }

        });
    }
    function loadUnitList(val,unitId,selectedUnit){
        for(var i in dictKeyArray){
            if(dictKeyArray[i].key === val){
                var units = dictKeyArray[i].data;
                var $opt_html = "";
                $.each(units, function (index, item) {
                    $opt_html += "<option value='" + item.id + "'>" + item.unitName + "</option>";
                });
                $("#"+unitId).empty().append($opt_html);
                if(selectedUnit){
                    $("#"+unitId).val(selectedUnit);
                }
                form.render('select');
                break;
            }
        }
    }


    form.verify({
        ip: [
            /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            ,'IP地址不符合规则'
        ]
    });

    table.on('tool(deviceTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                loadBuildingList($("#communityId2").val(),'blockId2','unitId2',data.blockId,data.unitId);
                $("#blockId2").empty();
                $("#unitId2").empty();
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                $("#updateId").val(data.id);
                $("#communityId2").val(data.communityId);
                $("#unitId2").val(data.unitId);
                $("#deviceName").val(data.deviceName);
                $("#account2").val(data.account);
                $("#password2").val(data.password);
                $("#ipAddress2").val(data.ipAddress);
                $("#ysSerialNum2").val(data.ysSerialNum);
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑门禁设备'
                    , area: ['55%', '70%']
                    , content: $('#updateDiv')
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/zxkDevice/delete',{id:data.id},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                table.reload('deviceTable');
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;
            case 'open':
                layer.confirm('确定要开门吗?', {
                }, function(){
                    layer.load();
                    var params = {serialNum:data.serialNum,productCode:data.productCode};
                    $.get('/zxkDevice/open',params,function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;
            case 'config':
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                $("#configId").val(data.id);
                $("#systemTime").val(formatTime(data.systemTime));
                $("#deviceIp").val(data.deviceIp);
                $("#devicePort").val(data.port);
                $("#replyVolume").val(data.replyVolume);
                form.render();
                layer.open({
                    type: 1
                    , title: '设备配置'
                    , area: ['35%', '60%']
                    , content: $('#configDiv')
                });
                break;

        }
    });

    form.on('submit(query_device)',function () {
        var name = $("#name").val();
        table.reload('deviceTable',{
            where: {name:name}
            ,page:  {
                curr:1
            }
        });
        return false;
    });


    $("#syncDevice").on('click', function (){
        layer.confirm('同步数据，是否继续？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            var index = layer.load(2, {
                shade: [0.4, '#000'],
                content: '同步中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '40px',
                        'width': '200px'
                    });
                }
            });
            $.post('/zxkDevice/syncData',{},function (res) {
                if(res.status === 200){
                    layer.msg(res.msg,{
                        time:1000,
                        end:function () {
                            reload();
                        }
                    });
                }else{
                    layer.msg(res.msg);
                }
                layer.close(index);
            });
        })
    });

    form.on('submit(upload_form)',function(data){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        data.field.communityName = $("#communityId").find("option:selected").text();
        data.field.blockName = $("#blockId").find("option:selected").text();
        data.field.unitName = $("#unitId").find("option:selected").text();
        data.field.deviceName = $("#unitId").find("option:selected").text();
        layer.load();
        $.ajax({
            type: 'post',
            url: '/zxkDevice/saveOrUpdate',
            data: data.field,
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },500);
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
                table.reload('deviceTable');
            },
        });
        return false;
    });

    form.on('submit(setName)',function(data){
        $("#setName").attr("disabled", true);
        $("#setName").attr("class", "layui-btn layui-btn-disabled");
        data.field.communityName = $("#communityId2").find("option:selected").text();
        data.field.blockName = $("#blockId2").find("option:selected").text();
        data.field.unitName = $("#unitId2").find("option:selected").text();
        $.ajax({
            type: 'post',
            url: '/zxkDevice/saveOrUpdate',
            data: data.field,
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },500);
                $("#setName").attr("disabled", false);
                $("#setName").attr("class", "layui-btn");
                table.reload('deviceTable');
            },
        });
        return false;
    });
    form.on('submit(setConfig)',function(data){
        $("#setConfig").attr("disabled", true);
        $("#setConfig").attr("class", "layui-btn layui-btn-disabled");
        $.ajax({
            type: 'post',
            url: '/zxkDevice/saveOrUpdate',
            data: data.field,
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },500);
                $("#setConfig").attr("disabled", false);
                $("#setConfig").attr("class", "layui-btn");
                table.reload('deviceTable');
            },
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });

    $("#cancel_form2").on('click',function (){
        layer.closeAll();
        return false;
    });
    $("#cancel_form3").on('click',function (){
        layer.closeAll();
        return false;
    });

});

function hasDictKey(key) {
    for(var i in dictKeyArray){
        if(dictKeyArray[i].key === key){
            return true;
        }
    }
    return false;
}
function parseStatus(status) {
    if(typeof status == "undefined" || status == null){
        return "未知";
    }
    switch (Number(status)) {
        case 0 : return "在线";
        case 1 : return "离线";
        default: return "未知";
    }

}
function reload(){
    location.reload();
}
function isBase64(str){
    if(str === '' || str === null || str.trim() === ''){
        return false;
    }
    try{
        return btoa(atob(str)) == str;
    }catch(err){
        return false;
    }
}